namespace Security.Business
{
    using System;
    using System.Text;
    using Security.Data;
    using System.IO;
    using System.Data.SqlClient;
    using Auditing.Business;
    using Auditing.Entities;
    using Common;
    using Microsoft.SqlServer.Management.Common;
    using Microsoft.SqlServer.Management.Smo;

    public class BackupService
    {
        public static void GenerateBackUp(string dbCnx, string backupsfolder, string notes)
        {
            BackupDAO dao = new BackupDAO();
            Security.Entities.Backup ent = new Security.Entities.Backup();
            string filename;
            ent.BackupKind = "Total";
            ent.Date = DateTime.Today;
            ent.Notes = notes;
            filename = string.Format("{0:yyyyMMdd_hhnnss}.bck", ent.Date);
            ent.Path = Path.Combine(backupsfolder, filename);
            ent.UserId = UserSession.UserId;
            CreateFullBackup(dbCnx, ent.Path);
            dao.Insert(ent);
            LogService.Log(LogType.Information,
                               string.Format("Back up creado: {0}.",
                               filename));
        }

        private static void CreateFullBackup(string dbCnx, string backupfile)
        {
                SqlConnection conn = new SqlConnection(dbCnx);
                conn.Open();
                ServerConnection SC = new ServerConnection(conn);
                Server srv = new Server(SC);
                BackupDeviceItem bdi = new BackupDeviceItem(backupfile, DeviceType.File);
                Backup bk = new Backup();
                bk.Devices.Add(bdi);
                bk.Action = BackupActionType.Database;
                bk.BackupSetDescription = "Full Backup_ECG";
                bk.BackupSetName = "ECG Backup";
                bk.Database = conn.Database.ToString();
                System.DateTime backupdate = new System.DateTime(2009, 5, 27);
                bk.ExpirationDate = backupdate;
                bk.LogTruncation = BackupTruncateLogType.Truncate;
                bk.Incremental = false;
                bk.SqlBackup(srv);
        }

        public static void RestoreBackUp(string dbCnx, Security.Entities.Backup backup, string dbPath)
        {
            try
            {
                RestoreDatabase(dbCnx, backup.Path, dbPath);

                LogService.Log(LogType.Warning,
                           string.Format("Back up restaurado a la fecha {0:u}.",
                           backup.Date));
            }
            catch (Exception)
            {
                throw new Common.Errors.DBError(string.Format("No se pudo restaurar la base de datos a la fecha {0:u}",
                           backup.Date));
            }
        }

        private static void RestoreDatabase(string dbCnx, string backupPath, string dbPath)
        {
            Restore restore = new Restore();
            BackupDeviceItem bdi = new BackupDeviceItem(backupPath, DeviceType.File);
            ServerConnection conn = new ServerConnection(dbCnx);
            Server srv = new Server(conn);
            restore.Devices.Add(bdi);
            restore.Database = conn.DatabaseName;
            restore.RelocateFiles.Add(new RelocateFile(conn.DatabaseName, dbPath));
            restore.Action = RestoreActionType.Database;
            restore.ReplaceDatabase = true;
            restore.SqlRestore(srv);
            srv.Refresh();
        }

        public static Security.Entities.UserSession UserSession
        {
            get { return SessionState.Current[Common.WebConstants.UserSession] as Security.Entities.UserSession; }
        }
    }
}
